﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using OLMS.DAL;
using OLMS.BLL;

namespace OLMS.Admin.Handlers
{
    /// <summary>
    /// UsersManagerHandler 的摘要说明
    /// </summary>
    public class UsersManagerHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            List<string> userStatusList = new List<string>()
            {
                "禁用","启用"
            };
            string json = "";
            if (context.Request["rl"] != null)
            {
                var list = RoleBLL.GetRolesList().Select(r => new
                {
                    RoleId = r.RoleId,
                    Name = r.Name
                }).ToList();
                json = JsonConvert.SerializeObject(list);
            }
            else
            {
                string rid = context.Request["rid"];
                string uid = context.Request["uid"];
                if (rid != null && uid!=null)
                {
                    //更改用户角色
                    int roleId = Convert.ToInt32(rid);
                    int userId = Convert.ToInt32(uid);
                    UserBLL.ChangeRole(userId, roleId);
                }
                else if(uid != null){
                    //启用或禁用用户
                    int userId = Convert.ToInt32(uid);
                    UserBLL.RemoveUser(userId);
                }
                var list = UserBLL.GetAdminUsersList().Select(u => new
                {
                    UserId = u.UserId,
                    LoginId = u.LoginId,
                    LoginPwd = u.LoginPwd,
                    UserName = u.UserName,
                    RoleId = u.RoleId,
                    Phone = u.Phone,
                    UserStatus = userStatusList[(int)u.UserStatus],
                    DateCreated = string.Format("{0:D}", u.DateCreated)
                }).ToList();
                json = JsonConvert.SerializeObject(list);
            }           
           
            context.Response.ContentType = "application/json";
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}